from django.shortcuts import render, redirect
from django.http import HttpResponse, Http404

from django.contrib.syndication.views import Feed
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from shanshan.models import Article
from blog.models import Tag

from datetime import datetime


def home(request):
    posts = Article.objects.all()
    paginator = Paginator(posts, 2)#实例化分页对象，每页显示2
    page = request.GET.get('page')
    try:
        post_list = paginator.page(page)
    except PageNotAnInteger:#页码不是整数
        post_list = paginator.page(1)
    except EmptyPage:#页码太大，无相应记录
        post_list = paginator.paginator(paginator.num_pages)
    return render(request, 'home.html', {'post_list': post_list})


def detail(request, id):
    try:
        post = Article.objects.get(id=str(id))
        tags = post.tag.all()
    except Article.DoesNotExist:
        raise Http404
    return render(request, 'post.html', {'post': post, 'tags': tags})


def archives(request):
    try:
        post_list = Article.objects.all()
    except Article.DoesNotExist:
        raise Http404
    return render(request, 'archives.html', {'post_list': post_list,
                                             'error': False})


def search_tag(request, tag):
    try:
        post_list = Article.objects.filter(category__iexact=tag)
    except Article.DoesNotExist:
        raise Http404
    return render(request, 'tag.html', {'post_list': post_list})


def about_me(request):
    return render(request, 'aboutme.html')


def blog_search(request):
    if 's' in request.GET:
        s = request.GET['s']
        if not s:
            return render(request, 'home.html')
        else:
            post_list = Article.objects.filter(title__icontains=s)
            return render(request, 'archives.html', {'post_list': post_list,
                                                     'error':
                                                     len(post_list) == 0})
    return redirect('/')


class RSSFeed(Feed):
    title = 'RSS feed - article'
    link = "feeds/posts/"
    description = 'RSS feed - blog posts'

    def items(self):
        return Article.objects.order_by('-date_time')

    def item_title(self, item):
        return item.title

    def item_pubdate(self, item):
        return item.date_time

    def item_description(self, item):
        return item.content
